package com.classes;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;

public class DBFactory {
	private static String message;
	private static Connection connect;
	private static final String CONFIG_FILE = "/properties/maxis.properties";
	private static final java.util.Properties appCfg = new java.util.Properties();
	
	public static String getMessage(){
		return "[DBFactory] " + DBFactory.message;
	}
	
	public static Connection getConnection(){
		return DBFactory.connect;
	}
	
	public static boolean connect(){
		
		try {
			if(DBFactory.connect == null || DBFactory.connect.isClosed() == true){
				try {
					InputStream stream = DBFactory.class.getResourceAsStream(CONFIG_FILE);
					if (stream != null){
						appCfg.load(stream);
					} else {
						System.out.println("DBFactory Input Stream is NULL");
					}
				} catch (Exception e) {
					System.err.println("DBFactory Error loading file " + CONFIG_FILE);
					System.err.println(e.getMessage());
					e.printStackTrace();
				}
				
				//jdbc:oracle:thin:@localhost:1521:xe
				String jdbc_str = appCfg.getProperty("JDBCDataSourceName");
				String db_user = appCfg.getProperty("DataBaseUserid");
				String db_pwd = appCfg.getProperty("DataBasePassword");
				
				Class.forName("oracle.jdbc.driver.OracleDriver");
				DBFactory.connect = DriverManager.getConnection(jdbc_str, db_user, db_pwd);
				
			}
			
			return true;
			
		} catch (Exception e){
			e.printStackTrace();
			DBFactory.message = e.getMessage();
			return false;
		}
	}
	
	public static boolean startTrans(){
		try {
			
			DBFactory.connect.setAutoCommit(false);
			return true;
			
		} catch (Exception e){
			e.printStackTrace();
			DBFactory.message = e.getMessage();
			return false;
		}
	}
	
	public static boolean commitTrans(){
		try {
			
			DBFactory.connect.commit();
			return true;
			
		} catch (Exception e){
			e.printStackTrace();
			DBFactory.message = e.getMessage();
			return false;
		}
	}
	
	public static boolean rollback(){
		try {
			
			DBFactory.connect.rollback();
			return true;
			
		} catch (Exception e){
			e.printStackTrace();
			DBFactory.message = e.getMessage();
			return false;
		}
	}
	
	public static boolean close(){
		try {
			if(DBFactory.connect != null) {
				DBFactory.connect.close();
				DBFactory.connect = null;
			}
			
			return true;
			
		} catch (Exception e){
			e.printStackTrace();
			DBFactory.message = e.getMessage();
			return false;
		}
	}
}
